package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContest;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: guozy
 * @Date: 2022/7/28 - 07 - 28 - 10:46
 * @Description: com.itheima.filter
 * @version: 1.0
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到了请求{}", requestURI);

        // 1.1定义不需要处理的URI
        String[] urls = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",// 移动端发送短信
                "/user/login"// 移动端登录
        };

        // 1.2判断请求是否需要处理
        boolean check = check(urls, requestURI);

        // 2.不需要处理,则直接放行
        if (check){
            filterChain.doFilter(request,response);
            log.info("不需要处理{}",requestURI);
            return;
        }

        // 3-1.判断登录状态,如果登录了,则放行
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null){
            //给线程工具类赋值
            BaseContest.setCurrentId(((Long) employee));
            // 打印日志
            log.info("用户已登录,用户的id为{}",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }

        // 3-2.判断C端登录状态,如果登录了,则放行
        Object user = request.getSession().getAttribute("user");
        if (user != null){
            // 打印日志
            log.info("用户已登录,用户的id为{}",user);
            //给线程工具类赋值
            BaseContest.setCurrentId(((Long) user));

            filterChain.doFilter(request,response);
            return;
        }
        // 4.未登录,则返回未登录的结果
        log.info("用户未登录,返回登录页面");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 检查路径是否需要过滤
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean check= PATH_MATCHER.match(url, requestURI);
            if (check){
                return check;
            }
        }
        return false;
    }
}
